﻿using KPIS.GERP.Models;
using KPIS.GERP.Models.HRM;
using KPIS.GERP.Models.ICM;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.WEB.GIMS.Class;
using System;
using System.Linq;
using System.Web.Mvc;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class MasContactController : Controller
    {
        #region MasContact 

        // [AllowAnonymous]
        public ActionResult Dump()
        {
            var db = new GERPContext(true);
            {
                for (int i = 0; i < 1000; i++)
                {
                    MasContact con1 = new MasContact();
                    con1.TaxCode = "123";
                    con1.NameTh = "asdjf dsajfksa fs;af j ส่หฟ ่กดสากหฟ ดสกหฟ ดสาหฟ กดส่หฟ สาด่หฟ ดสาหฟีด ้สกหฟ่ดสา้หฟสา่เ้หฟวสา";
                    con1.RecordStatus = "U";
                    con1.ConGrpId = 1;
                    con1.CreatedBy = 1;
                    con1.CreatedWhen = DateTime.Now;
                    db.MasContacts.Add(con1);
                }
                db.SaveChanges();
            }
            return Content("Fin");
        }
        
        private const int ContactCategoryDefault = 1;

        public string base64Decode(string data)
        {
            try
            {
                System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
                System.Text.Decoder utf8Decode = encoder.GetDecoder();

                byte[] todecode_byte = Convert.FromBase64String(data);
                int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
                char[] decoded_char = new char[charCount];
                utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
                string result = new String(decoded_char);
                return result;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Decode" + e.Message);
            }
        }

        public ActionResult Index(int? category, bool nolayout = false)
        {
            if (!category.HasValue)
                return RedirectToAction("_Error404", "Home");// HttpNotFound();// RedirectToAction("ShowSomeMessage", "Home", new { message = "ข้อมูลที่จำเป็นมีไม่ครบ", urlBack = Url.Action("Index", new { category = ContactCategoryDefault }) });

            var service = new MasContactService.MasContactServiceClient();
            ViewBag.Category = category;
            ViewBag.Layout = nolayout ? "~/Views/Shared/_EmptyLayout.cshtml": "~/Views/Shared/_SiteLayout.cshtml" ;
            ViewBag.NoLayout = nolayout;
            return View(service.SelectContact(new MasContact { RecordStatus = "!D", ConCategory = 0 }, new[] { "ContactGroup" }));//category.Value
        }

        // [AllowAnonymous]
        public ActionResult IndexF(int? category, string UserName, string Password, bool nolayout = false)
        {
            var PasswordF = Password;
            var PasswordN = base64Decode(PasswordF);
            if (!string.IsNullOrWhiteSpace(UserName) && !string.IsNullOrWhiteSpace(PasswordN))
            {
                Employee employee;
                using (var us = new UserService.UserServiceClient())
                {
                    var user = us.GetUserByUserCode(UserName);

                    if (user == null)
                    {
                        //// Remark: หากมาถึงตรงนี้ แบบว่าตาราง SysUser ไม่มีข้อมูลของผู้ใช้นี้ แต่มีอยู่ในตาราง UserProfile ของระบบ MemberShip
                        //// ไม่ควรเกิดขึ้น เพราะหากสร้างหรือลบ User ก็ควรทำทั้ง WebSecurityX และ SysUser ไปด้วยกัน
                        //var notFoundInSysUserExc = new Exception("Not found this user in SysUser");

                        //// Option#1 throw error
                        //// throw notFoundInSysUserExc;

                        //// Option@2 show as message error in model
                        //ModelState.AddModelError("", notFoundInSysUserExc.Message);

                        //WebSecurityX.Logout();
                        GimsMembership.Logout();

                        //return View(model);
                        throw new Exception("Not found this user in SysUser");
                    }

                    employee = new UserService.UserServiceClient().GetEmployeeByUser(user.UserId);
                }
                if (employee == null)
                {
                    //var notFoundInEmployeeExc = new Exception("Not found current employee in database");

                    //ModelState.AddModelError("", notFoundInEmployeeExc.Message);

                    //WebSecurityX.Logout();
                    GimsMembership.Logout();

                    //return View(model);
                    throw new Exception("Not found current employee in database");
                }

                using (var gs = new GerpAuthenService.GerpAuthenServiceClient())
                {
                    gs.Login(GimsMembership.CurrentEmpId, GimsUtilities.ClientIp,
                             GimsUtilities.ThisSystemId, UserName, employee.FullName, employee.PosId);
                }
            }

            if (!category.HasValue)
                return RedirectToAction("_Error404", "Home");// HttpNotFound();// RedirectToAction("ShowSomeMessage", "Home", new { message = "ข้อมูลที่จำเป็นมีไม่ครบ", urlBack = Url.Action("Index", new { category = ContactCategoryDefault }) });

            var service = new MasContactService.MasContactServiceClient();
            ViewBag.Category = category;
            ViewBag.Layout = nolayout ? "~/Views/Shared/_EmptyLayout.cshtml": "~/Views/Shared/_SiteLayout.cshtml" ;
            ViewBag.NoLayout = nolayout;

            return View("Index", service.SelectContact(new MasContact { RecordStatus = "!D", ConCategory = category.Value }, new[] { "ContactGroup" }));
        }

        public ActionResult Details(int id, int? category = null, bool nolayout = false)
        {
            var service = new MasContactService.MasContactServiceClient();
            var model = service.SelectContact(new MasContact { ConId = id }, new[] { "ContactGroup", "ContactStatus", "VatType" }).FirstOrDefault();
            
            ViewBag.Category = category;
            ViewBag.Nolayout = nolayout;
            ViewBag.Layout = nolayout ? "~/Views/Shared/_EmptyLayout.cshtml": "~/Views/Shared/_SiteLayout.cshtml" ;

            return View(model);
        }

        public ActionResult PopupDetails(int id)
        {
            var service = new MasContactService.MasContactServiceClient();
            var model = service.SelectContact(new MasContact { ConId = id }, new[] { "ContactGroup", "ContactStatus", "VatType" }).FirstOrDefault();

            return View(model);
        }

        public ActionResult Create(int? category, bool nolayout = false)
        {
            var model = new MasContact();
            model.ConCategory = category ?? 2;
            model.ConStatusId = 39;
            model.ConGrpId = 36;
            ViewBag.Layout = nolayout ? "~/Views/Shared/_EmptyLayout.cshtml": "~/Views/Shared/_SiteLayout.cshtml" ;
            ViewBag.NoLayout = nolayout;

            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Create(MasContact model, int? category, bool nolayout = false)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new MasContactService.MasContactServiceClient();

                    // 54รวมภาษี, 55แยกภาษี, 56ยกเว้นภาษี
                    if (model.VatTypeId != 56 && string.IsNullOrWhiteSpace(model.TaxCode))
                    {
                        ModelState.AddModelError("", "กรณีไม่ได้ยกเว้นภาษี กรุณากรอกเลขประจำตัวผู้เสียภาษี!!");
                        ViewBag.Layout = nolayout ? "~/Views/Shared/_EmptyLayout.cshtml" : "~/Views/Shared/_SiteLayout.cshtml";
                        ViewBag.nolayout = nolayout;
                        ViewBag.category = category;
                        return View(model);
                    }

                    var criteria = new MasContact {TaxCode = model.TaxCode,RecordStatus = "!" + RecordStatus.DeletedStatus};
                    if (model.VatTypeId != 56 && service.SelectContact(criteria, null).Length > 0)
                    {
                        ModelState.AddModelError("", "มีเลขประจำตัวผู้เสียภาษีนี้ในระบบแล้ว!!");
                        ViewBag.Layout = nolayout ? "~/Views/Shared/_EmptyLayout.cshtml" : "~/Views/Shared/_SiteLayout.cshtml";
                        ViewBag.nolayout = nolayout;
                        ViewBag.category = category;
                        return View(model);
                    }

                    var id = service.InsertContact(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Details", new { id = id, nolayout = nolayout });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            ModelState.AddModelError("", "พบข้อผิดพลาดขณะบันทึกข้อมูล!!");
            ViewBag.Layout = nolayout ? "~/Views/Shared/_EmptyLayout.cshtml": "~/Views/Shared/_SiteLayout.cshtml";
            ViewBag.nolayout = nolayout;
            ViewBag.category = category;
            return View(model);
        }

        public ActionResult Edit(int id, bool nolayout = false)
        {
            var service = new MasContactService.MasContactServiceClient();
            var model = service.SelectContact(new MasContact { ConId = id }, null).FirstOrDefault();

            var service2 = new IcmMasLookUpService.IcmMasLookUpServiceClient();
            ViewBag.ContactGroupList = service2.MasLookUpSelectList(IcmMasLookUpType.LookUpType.ContactGroup);
            ViewBag.VatTypeList = service2.MasLookUpSelectList(IcmMasLookUpType.LookUpType.VatType);
            ViewBag.Layout = nolayout ? "~/Views/Shared/_EmptyLayout.cshtml": "~/Views/Shared/_SiteLayout.cshtml" ;
            ViewBag.NoLayout = nolayout;

            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(int id, int? category, MasContact model, bool nolayout = false)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new MasContactService.MasContactServiceClient();

                    //ให้บันทึกได้แม้มีเลข Tax Code ซ้ำในระบบ Req 14 ของเดือนตุลาคม 2557
                    //var criteria = new MasContact { TaxCode = model.TaxCode, RecordStatus = "!" + RecordStatus.DeletedStatus };
                    // 54รวมภาษี, 55แยกภาษี, 56ยกเว้นภาษี
                    if (model.VatTypeId != 56 && string.IsNullOrWhiteSpace(model.TaxCode))
                    {
                        ModelState.AddModelError("", "กรณีไม่ได้ยกเว้นภาษี กรุณากรอกเลขประจำตัวผู้เสียภาษี!!");
                        ViewBag.Layout = nolayout ? "~/Views/Shared/_EmptyLayout.cshtml" : "~/Views/Shared/_SiteLayout.cshtml";
                        ViewBag.nolayout = nolayout;
                        ViewBag.category = category;
                        return View(model);
                    }

                    //ให้บันทึกได้แม้มีเลข Tax Code ซ้ำในระบบ Req 14 ของเดือนตุลาคม 2557
                    //if (model.VatTypeId != 56 &&
                    //    service.SelectContact(criteria, null).Any(m => m.ConId != model.ConId))
                    //{
                    //    ModelState.AddModelError("", "มีเลขประจำตัวผู้เสียภาษีนี้ในระบบแล้ว!!");
                    //    ViewBag.Layout = nolayout ? "~/Views/Shared/_EmptyLayout.cshtml" : "~/Views/Shared/_SiteLayout.cshtml";
                    //    ViewBag.nolayout = nolayout;
                    //    ViewBag.category = category;
                    //    return View(model);
                    //}
                    
                    service.UpdateContact(model, GimsMembership.CurrentEmpId);

                    return RedirectToAction("Details", new { id, noLayout = nolayout });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            ModelState.AddModelError("", "พบข้อผิดพลาดขณะบันทึกข้อมูล!!");
            ViewBag.Layout = nolayout ? "~/Views/Shared/_EmptyLayout.cshtml": "~/Views/Shared/_SiteLayout.cshtml" ;
            ViewBag.NoLayout = nolayout;
            ViewBag.category = category;

            return View(model);
        }

        public ActionResult Delete(int id, int category, bool nolayout = false)
        {
            try
            {
                var service = new MasContactService.MasContactServiceClient();
                service.DeleteContact(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("Index", new { category = category, nolayout = nolayout });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteAll(int[] deleteIds)
        {
            try
            {
                if (deleteIds != null)
                {
                    var service = new MasContactService.MasContactServiceClient();

                    foreach (int delete in deleteIds)
                    {
                        service.DeleteContact(delete, Class.GimsMembership.CurrentEmpId);
                    }
                }

                ModelState.AddModelError("", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");

                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }
        }
        #endregion

        #region MasContactBank
        public ActionResult IndexBank(int ConId)
        {
            var service = new MasContactService.MasContactServiceClient();
            ViewBag.ConId = ConId;
            return View(service.SelectContactBank(new MasContactBank { ConId = ConId, RecordStatus = "!D" }, new[] { "MasBankBranch.Bank" }));
        }

        public ActionResult DetailsBank(int id)
        {
            var service = new MasContactService.MasContactServiceClient();
            var model = service.SelectContactBank(new MasContactBank { ConBankId = id }, new[] { "MasBankBranch.Bank" }).FirstOrDefault();

            return View(model);
        }

        public ActionResult CreateBank(int ConId)
        {
            var model = new MasContactBank();
            model.ConId = ConId;

            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateBank(MasContactBank model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    model.MasContact = null;
                    model.MasBankBranch = null;

                    var service = new MasContactService.MasContactServiceClient();
                    var id = service.InsertContactBank(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("DetailsBank", new { id = id });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return View(model);
        }

        public ActionResult EditBank(int id)
        {
            var service = new MasContactService.MasContactServiceClient();
            var model = service.SelectContactBank(new MasContactBank { ConBankId = id }, new[] { "MasBankBranch" }).FirstOrDefault();

            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult EditBank(int id, MasContactBank model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    model.MasContact = null;
                    model.MasBankBranch = null;

                    var service = new MasContactService.MasContactServiceClient();
                    service.UpdateContactBank(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("DetailsBank", new { id = id });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return View(model);
        }

        public ActionResult DeleteBank(int id)
        {
            try
            {
                var service = new MasContactService.MasContactServiceClient();
                var ConId = service.SelectContactBank(new MasContactBank() { ConBankId = id }, null).FirstOrDefault().ConId;
                service.DeleteContactBank(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("IndexBank", new { ConId = ConId });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteAllBank(int[] deleteIds)
        {
            try
            {
                if (deleteIds != null)
                {
                    var service = new MasContactService.MasContactServiceClient();

                    foreach (int delete in deleteIds)
                    {
                        service.DeleteContactBank(delete, Class.GimsMembership.CurrentEmpId);
                    }
                }

                ModelState.AddModelError("Error", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");

                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("Error", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }
        }

        public ActionResult GetBankBranchList(int BankId)
        {
            var service = new MasBankService.MasBankServiceClient();
            var result = service.SelectListBankBranch(new Models.FIM.MasBankBranch() { BankId = BankId, RecordStatus = "!D" });
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region MasContactPartner
        public ActionResult IndexPartner(int ConId)
        {
            var service = new MasContactService.MasContactServiceClient();
            ViewBag.ConId = ConId;

            return View(service.SelectContactPartner(new MasContactPartner { ConId = ConId, RecordStatus = "!D" }, null));
        }

        public ActionResult DetailsPartner(int id)
        {
            var service = new MasContactService.MasContactServiceClient();
            var model = service.SelectContactPartner(new MasContactPartner { ConPartId = id}, null).FirstOrDefault();
            ViewBag.ConId = model.ConId;

            return View(model);
        }

        public ActionResult CreatePartner(int ConId)
        {
            var model = new MasContactPartner();
            //ViewBag.ConId = ConId;
            model.ConId = ConId;

            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreatePartner(MasContactPartner model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new MasContactService.MasContactServiceClient();
                    var id = service.InsertContactPartner(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("DetailsPartner", new { id = id });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return View(model);
        }

        public ActionResult EditPartner(int id)
        {
            var service = new MasContactService.MasContactServiceClient();
            var model = service.SelectContactPartner(new MasContactPartner { ConPartId = id}, null).FirstOrDefault();

            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult EditPartner(int id, MasContactPartner model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new MasContactService.MasContactServiceClient();
                    service.UpdateContactPartner(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("DetailsPartner", new { id = id });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return View(model);
        }

        public ActionResult DeletePartner(int id)
        {
            try
            {
                var service = new MasContactService.MasContactServiceClient();
                var ConId = service.SelectContactPartner(new MasContactPartner() { ConPartId = id }, null).FirstOrDefault().ConId;
                service.DeleteContactPartner(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("IndexPartner", new { ConId = ConId });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteAllPartner(int[] deleteIds)
        {
            try
            {
                if (deleteIds != null)
                {
                    var service = new MasContactService.MasContactServiceClient();

                    foreach (int delete in deleteIds)
                    {
                        service.DeleteContactPartner(delete, Class.GimsMembership.CurrentEmpId);
                    }
                }

                ModelState.AddModelError("Error", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");

                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("Error", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }
        }
        #endregion
    }
}
